package ita.class1.group2.supermarket.customer.dao;

import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.dao.impl.BaseDaoImpl;
import ita.class1.group2.supermarket.common.util.ConnectionManager;
import ita.class1.group2.supermarket.customer.pojo.Product;
import ita.class1.group2.supermarket.customer.pojo.StoreInformation;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class ProductDao extends BaseDaoImpl<Product, String> {

    @Autowired
    private ConnectionManager connectionManager;

    public List<Product> findProductsBySId(String sId, Integer pageIndex, Integer pageCount){
        List<Product> products = new ArrayList<>();
        Integer nttotal = pageCount * pageIndex;
        Integer gttotal = pageCount * (pageIndex - 1);
        String sql = "select * from (select e.*, rownum rn from (select * from mc_product where sid = ? )e where rownum <="+nttotal+") where rn >"+gttotal ;
        System.out.println("sql:"+sql);
        try {
            PreparedStatement statement = connectionManager.getConnection().prepareStatement(sql);
            statement.setString(1,sId);
            ResultSet rs = statement.executeQuery();
            while(rs.next()){
                Product product = new Product(rs.getString("id"),rs.getString("sid"),rs.getString("name"),
                        rs.getString("description"),rs.getString("images"),rs.getDouble("price"),
                        rs.getInt("quantity"),rs.getDate("create_time"));
                products.add(product);
            }
            System.out.println("size:"+products.size());
            statement.close();
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return products;
    }

    public int findProductsCountBySId(String sId) {
        int count = 0;
        String sql = "select count(*) from mc_product where sid = ?";
        try {
            PreparedStatement statement = connectionManager.getConnection().prepareStatement(sql);
            statement.setString(1,sId);
            ResultSet rs = statement.executeQuery();
            rs.next();
            count = rs.getInt(1);
            System.out.println("count:"+count);
            rs.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
